package com.catmiao.spark.stream

import com.catmiao.spark.stream.SparkStreaming12_Req1_BlackList.AdClickData
import com.catmiao.spark.util.JDBCUtil
import org.apache.kafka.clients.consumer.{ConsumerConfig, ConsumerRecord}
import org.apache.spark.SparkConf
import org.apache.spark.streaming.dstream.{DStream, InputDStream}
import org.apache.spark.streaming.kafka010.{ConsumerStrategies, KafkaUtils, LocationStrategies}
import org.apache.spark.streaming.{Seconds, StreamingContext}

import java.text.SimpleDateFormat
import java.util.Date

/**
 * @title: SparkStreaming01_WordCount
 * @projectName spark_study
 * @description: 广告点击量实时统计、实时统计每天各地区各城市各广告的点击总流量，并将其存入 MySQL
 * @author ChengMiao
 * @date 2024/3/25 00:31
 */
object SparkStreaming12_Req2 {

  def main(args: Array[String]): Unit = {


    // 创建环境
    val sparkConf: SparkConf = new SparkConf().setMaster("local[*]").setAppName("SparkStreaming")
    //  param1 : 环境配置，SparkConf
    //  param2 ： 采集周期【批量处理周期】
    val ssc = new StreamingContext(sparkConf, Seconds(3))

    //3.定义 Kafka 参数
    val kafkaPara: Map[String, Object] = Map[String, Object](
      ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG ->
        "localhost:9092",
      ConsumerConfig.GROUP_ID_CONFIG -> "test",
      "key.deserializer" ->
        "org.apache.kafka.common.serialization.StringDeserializer",
      "value.deserializer" ->
        "org.apache.kafka.common.serialization.StringDeserializer"
    )
    //4.读取 Kafka 数据创建 DStream
    val kafkaDStream: InputDStream[ConsumerRecord[String, String]] =
      KafkaUtils.createDirectStream[String, String](ssc,
        LocationStrategies.PreferConsistent,
        ConsumerStrategies.Subscribe[String, String](Set("first"), kafkaPara))



    val sdf: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd")


    val dataDs: DStream[AdClickData] = kafkaDStream.map(
      data => {
        val d: String = data.value()
        val value = d.split(" ")
        AdClickData(value(0), value(1), value(2), value(3), value(4))
      }
    )

    // 单个批次内对数据进行按照天维度的聚合统计;
    val value: DStream[((String, String, String, String), Int)] = dataDs.map(
      data => {
        val time = data.ts
        val area = new String(data.area.getBytes("UTF-8"),"UTF-8")
        val city = new String(data.city.getBytes("UTF-8"),"UTF-8")
        val ad = data.ad

        val date = sdf.format(new Date(time.toLong))
        ((date, area, city, ad), 1)
      }
    ).reduceByKey(_ + _)

    // 结合 MySQL 数据跟当前批次数据更新原有的数据
    value.foreachRDD(
      rdd => {
        rdd.foreachPartition(
          iter => {
            val conn = JDBCUtil.getConnection
            iter.foreach{
              case ((date, area, city, ad), count) => {
                val sql =
                  """
                    | insert into  area_city_ad_count (dt,area,city,adid,count)
                    | values(?,?,?,?,?)
                    | on duplicate key
                    | update count = count + ?
                    |""".stripMargin

                JDBCUtil.executeUpdate(conn,sql,Array(date,area,city,ad,count,count))
              }
            }
            conn.close()
          }
        )
      }
    )


    // 1. 启动采集器
    ssc.start()



    // 2. 等待采集器的关闭
    ssc.awaitTermination()
  }


}
